package com.example.homework8.fragment;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.homework8.R;
import com.example.homework8.adapter.PlanAdapter;
import com.example.homework8.adapter.RecordAdapter2;
import com.example.homework8.adapter.TagAdapter;
import com.example.homework8.adapter.TagAdapter2;
import com.example.homework8.bean.PlanInfo;
import com.example.homework8.bean.RecordInfo;
import com.example.homework8.bean.TagBean;
import com.example.homework8.database.MySQLHelper;
import com.example.homework8.database.PlanDBHelper;
import com.example.homework8.database.RecordDBHelper;
import com.example.homework8.utils.SharedUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PlanFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlanFragment extends Fragment implements View.OnClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    public final  String TAG = "GoodsListActivyt";
    private TextView tv_count;
    private FloatingActionButton addbutton;
    private LinearLayout ll_chananel;
    private  int mCount;
    private PlanDBHelper planhelper ;

    private RecordDBHelper recordhelper ;

    public PlanFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }

    }

    private String mFirst = "true"; // 是否首次打开
    private ListView listview = null;
    SearchView searchView ;
    ArrayList<RecordInfo> recordInfoArrayList ,alllist;

    public void setDate (  ArrayList<RecordInfo>  date) {
        this.recordInfoArrayList = date;
        notify();
    }
    ListView catelist;
    ArrayList<String> tages =new ArrayList<>();
    private MySQLHelper mySQLiteOpenHelpter = null;
    ArrayList<TagBean> tagBeanList ;
    private void queryTag(){

        if (mySQLiteOpenHelpter == null){
            mySQLiteOpenHelpter = new MySQLHelper(getActivity());
        }

        SQLiteDatabase mDataBase
                = mySQLiteOpenHelpter.getWritableDatabase();
        Cursor cursor = mDataBase.rawQuery("select * from tag", null);
        //4.解析结果集
        //判断结果集是否有效
        if (cursor != null && cursor.getCount() > 0) {
            ArrayList<TagBean> list = new ArrayList<>();
            while (cursor.moveToNext()) {//游标是否继续向下移动
                TagBean bean = new TagBean();
                bean.setSelected(false);
                //通过列的索引获取对应的数据
                bean.setId(cursor.getInt(cursor.getColumnIndex("tag_id")));
                bean.setText(cursor.getString(cursor.getColumnIndex("describe")));
                list.add(bean);
            }
            //关闭cursor
            cursor.close();
            tagBeanList = list;
            TagAdapter2 tagAdapter = new TagAdapter2(getActivity(),tagBeanList);
            catelist.setAdapter(tagAdapter);
            catelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    for (TagBean tagbean: tagBeanList) {
                        tagbean.setSelected(false);
                    }
                    tagBeanList.get(i).setSelected(true);
                    tagAdapter.notifyDataSetChanged();
                    if(tages.contains(tagBeanList.get(i).getText())){
                        tages.remove(i);
                    }else{
                        tages.add(tagBeanList.get(i).getText());
                    }
                }
            });
            tagAdapter.notifyDataSetChanged();
         }else {
            Toast.makeText(getActivity(),"无标签",Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_plan, container, false);
        addbutton = view.findViewById(R.id.addbutton);
        catelist = view.findViewById(R.id.catelist);
        listview = view.findViewById(R.id.listview);
        addbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.id_content, new AddRecordFragment(), null)
                        .addToBackStack(null)
                        .commit();
            }
        });

        recordhelper = RecordDBHelper.getInstance(getActivity(), 1);
        recordhelper.openReadLink();
        planhelper = PlanDBHelper.getInstance(getActivity(), 1);
        planhelper.openWriteLink();
        String name = SharedUtil.getIntance(getActivity()).readShared("loginuser","未登录");
        ArrayList<RecordInfo> recordInfoArrayList = recordhelper.query("username =" +name );
        alllist = recordInfoArrayList;
        for (RecordInfo recordInfo: recordInfoArrayList) {
            Log.d(TAG, "onCreateView: " + recordInfo.toString());
        }
        RecordAdapter2 recordAdapter2 = new RecordAdapter2(recordInfoArrayList, getActivity());
//        Log.d(TAG, "onCreateView: " + recordInfoArrayList.size());
//        listview.setAdapter(recordAdapter2);
//        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//
//            }
//        });
//        recordAdapter2.notifyDataSetChanged();
        searchView = view.findViewById(R.id.searchView);
        name = SharedUtil.getIntance(getActivity()).readShared("loginuser","未登录");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if(tages.size() <=0) {
                    Toast.makeText(getActivity(),"请选择分类!",Toast.LENGTH_SHORT).show();
                    return false;
                }
                ArrayList<RecordInfo> planInfoArrayList = new ArrayList<>();
                for (RecordInfo pp: alllist) {
                    Log.d(TAG, "onQueryTextChange: " + pp.cate);
                    if(tages.contains(pp.cate)){
                        if(pp.name.startsWith(s) ){
                            planInfoArrayList.add(pp);
                            Log.d(TAG, "onQueryTextChange: equal" + pp.toString());
                        }
                    }
                }
                Log.d(TAG, "onQueryTextChange: after search list is "  + planInfoArrayList.size()+ " :"+ planInfoArrayList.toString());

                recordAdapter2.setmData(planInfoArrayList);
                listview.setAdapter(recordAdapter2);
                return true;
            }
        });

        queryTag();
        return  view;
    }



    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.iv_cart){

        }
    }


}